package cn.yeyiu.util;

import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;

import cn.yeyiu.util.bean.MangaDetail;
import cn.yeyiu.util.bean.TimeVideoInfo;
import cn.yeyiu.util.bean.VideoInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetUtil {

    public static String getByUrl(String str, Map<String, String> header) {
        try {
            Request.Builder builder = new Request.Builder().url(str).get();
            for (String key : header.keySet()) {
                builder = builder.header(key, header.get(key));
            }
            Response execute = new OkHttpClient().newCall(
                    builder.build()
            ).execute();
            if (execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException unused) {
            System.out.println(unused.getMessage());
        }
        return null;
    }

    public static String getByUrl(String url) {
        try {
            Response execute = new OkHttpClient().newCall(
                    new Request.Builder()
                            .url(url)
                            .get()
                            .build()
            ).execute();
            if (execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (Exception unused) {
            System.out.println(unused.getMessage());
        }
        return null;
    }


    public static String getUrlWhile(String url, int time) {
        String html;
        while ((html = NetUtil.getByUrl(url)) == null) {
            System.out.println(url);
            if (--time < 0) {
                return "";
            }
            try {
                Thread.sleep(500);
            } catch (Exception ignore) {
            }
        }
        return html;
    }

    public static String postByUrl(String str, JSONObject formBodyJson, boolean isJson, Map<String, String> header) {
        try {
            if (formBodyJson == null) {
                formBodyJson = new JSONObject();
            }
            RequestBody requestBody;
            if (isJson) {
                MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
                requestBody = RequestBody.create(formBodyJson.toJSONString(), mediaType);
            } else {
                FormBody.Builder builder = new FormBody.Builder();
                for (String key : formBodyJson.keySet()) {
                    builder = builder.add(key, formBodyJson.getString(key));
                }
                requestBody = builder.build();
            }

            Request.Builder resbuilder = new Request.Builder().url(str).post(requestBody);

            for (String key : header.keySet()) {
                resbuilder = resbuilder.header(key, header.get(key));
            }
            resbuilder = resbuilder.header("Content-Type", "application/json;charset=utf-8");
            Response execute = new OkHttpClient().newCall(
                    resbuilder.build()).execute();
            if (execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException unused) {
        }
        AndroidUtil.toast("网络请求失败，请检查连接！");
        return null;
    }

    public static String postByUrl(String str, JSONObject formBodyJson, boolean isJson) {
        try {
            if (formBodyJson == null) {
                formBodyJson = new JSONObject();
            }
            RequestBody requestBody;
            if (isJson) {
                MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
                requestBody = RequestBody.create(formBodyJson.toJSONString(), mediaType);
            } else {
                FormBody.Builder builder = new FormBody.Builder();
                for (String key : formBodyJson.keySet()) {
                    builder = builder.add(key, formBodyJson.getString(key));
                }
                requestBody = builder.build();
            }

            Response execute = new OkHttpClient().newCall(
                    new Request.Builder()
                            .url(str)
                            .post(requestBody)
                            .build()).execute();
            if (execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException unused) {
        }
        AndroidUtil.toast("网络请求失败，请检查连接！");
        return null;
    }

    public static boolean isReachable(String str) {
        try {
            return InetAddress.getByName(str).isReachable(500);
        } catch (IOException unused) {
            return false;
        }
    }

    public static int isWebWorking(String str) {
        if (!isReachable(str)) {
            return -1;
        }
        return getByUrl(new StringBuilder().append("http://").append(str).append(":").append(NetConfig.getPort()).toString()) != null ? 1 : 0;
    }

    public static String getQuickServerIP() {
        String[] strArr = NetConfig.quickIps;
        for (String str : strArr) {
            if (isWebWorking(str) == 1) {
                return str;
            }
        }
        return NetConfig.FAIL_IP;
    }

    public static String getServerIP() {
        String[] strArr = {"192.168.1.", "192.168.2.", "192.168.43."};
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < 3; i++) {
            String str = strArr[i];
            if (isReachable(str + "1")) {
                for (int i2 = 2; i2 < 256; i2++) {
                    String str2 = str + i2;
                    Log.d("服务器：", "getIP: " + str2);
                    int isWebWorking = isWebWorking(str2);
                    if (isWebWorking == 1) {
                        return str2;
                    }
                    if (isWebWorking == 0) {
                        arrayList.add(str2);
                    }
                }
                continue;
            }
        }
        Log.d("网络初始化：", "getServerIP: fail");
        return NetConfig.FAIL_IP;
    }

    public static void downloadVideo(Context context, VideoInfo videoInfo) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoInfo.videoSrc));
        String fileMd5 = StringUtil.md5(videoInfo.title) + videoInfo.videoSrc.substring(videoInfo.videoSrc.length() - 4);
        request.setDestinationInExternalFilesDir(context, "download/" + videoInfo.type, fileMd5);
        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
        new AlertDialog.Builder(context)
                .setTitle("♪(^∇^*)")
                .setMessage(videoInfo.videoSrc + "\n>> 已加入下载队列！")
                .setPositiveButton("OK", (DialogInterface.OnClickListener) null)
                .create().show();
        // 保存下载记录
        ExternalJSONFile.saveDatas(context, "download_" + videoInfo.type, new TimeVideoInfo(videoInfo));
    }
}
